<template>
  <div class="review-app">
    <!-- 头部区域 -->
    <header class="app-header">
      <div class="container header-container">
        <div class="logo-container">
          <div class="placeholder-logo"><img src="/src//assets/images/4a3ece7aca9c3eee3c352f9b5ec3e6a8.jpg" alt="系统logo" class="logo-img"></div>
        </div>
        <div class="system-title">
          <h1>AI辅助学习系统-英语模块(词汇复习)</h1>
        </div>
        <div class="theme-control">
          <div class="function-buttons">
            <button class="func-btn" title="返回词汇列表" @click="goTo('/english/vo')">
              <span>📚</span>
            </button>
            <button class="theme-btn" :class="isDarkMode ? 'dark' : 'light'" @click="toggleTheme" title="切换主题">
              <span>{{ isDarkMode ? '🌞' : '🌙' }}</span>
            </button>
          </div>
        </div>
      </div>
    </header>

    <!-- 主内容区 -->
    <main class="review-content">
      <div class="container">
        <!-- 词汇本选择 -->
        <div class="book-selector" v-if="!loading || bookList.length > 0">
          <select 
            v-model="selectedBookId" 
            @change="handleBookChange" 
            :disabled="loading"
            class="book-select"
          >
            <option value="">-- 选择复习词汇本 --</option>
            <option v-for="book in bookList" :key="book.bookId" :value="book.bookId">
              {{ book.bookName || `词汇本 ${book.bookId}` }}
            </option>
          </select>
          <span class="error-message" v-if="errorMsg">{{ errorMsg }}</span>
        </div>

        <!-- 加载状态 -->
        <div class="loading-indicator" v-if="loading && bookList.length === 0">
          加载中...请稍候
        </div>

        <!-- 复习进度 -->
        <div class="review-progress" v-if="!loading && selectedBookId">
          <div class="progress-bar" :style="{ width: progressPercentage + '%' }"></div>
          <div class="progress-text">
            {{ currentWordIndex + 1 }} / {{ reviewWords.length }} 单词
          </div>
        </div>

        <!-- 单词学习卡片 -->
        <div class="word-card" v-if="currentStep === 'word' && !loading && selectedBookId && currentWord">
          <div class="card-inner">
            <div class="word-display">
              <h2 class="review-word">{{ currentWord.word }}</h2>
              <p class="review-pronunciation">{{ currentWord.pronunciation }}</p>
              <p class="review-chinese" v-if="currentWord.chinese">{{ currentWord.chinese }}</p>
            </div>
            
            <div class="word-details" :class="{ active: showDetails }">
              <p class="review-definition">{{ currentWord.definition }}</p>
              <p class="review-example"><strong>例句：</strong>{{ currentWord.example || '无例句' }}</p>
            </div>
            
            <button 
              class="action-btn toggle-details-btn" 
              @click="showDetails = !showDetails"
            >
              {{ showDetails ? '隐藏释义' : '显示释义' }}
            </button>
            
            <div class="review-actions" v-if="showDetails">
              <button class="action-btn know-btn" @click="markAsKnown">
                已掌握
              </button>
              <button class="action-btn unknown-btn" @click="markAsUnknown">
                未掌握
              </button>
            </div>
          </div>
        </div>

        <!-- 拼写练习 -->
        <div class="spelling-practice" v-if="currentStep === 'spelling' && !loading && selectedBookId">
          <h3 class="spelling-title">拼写练习</h3>
          <p class="spelling-hint">请拼写单词：<strong>{{ currentWord.word.charAt(0) }}{{ '_'.repeat(currentWord.word.length - 1) }}</strong></p>
          
          <input 
            type="text" 
            v-model="spellingInput" 
            class="spelling-input" 
            placeholder="输入单词拼写..."
            @keyup.enter="checkSpelling"
            ref="spellingInputRef"
            :class="{ 'correct-input': spellingResult === true, 'incorrect-input': spellingResult === false }"
            :disabled="spellingResult === true"
          >
          
          <div class="spelling-feedback" v-if="spellingResult !== null">
            <p v-if="spellingResult" class="correct">✓ 拼写正确！即将自动进入下一个单词...</p>
            <p v-else class="incorrect">✗ 拼写错误，正确答案是：<strong>{{ currentWord.word }}</strong></p>
          </div>
          
          <div class="spelling-actions" v-if="spellingResult === false || nextWordTimer === 0">
            <button class="action-btn retry-btn" @click="resetSpelling" v-if="spellingResult === false">
              再试一次
            </button>
            <button class="action-btn next-btn" @click="nextWord" :disabled="spellingResult === null">
              下一个
            </button>
          </div>
          
          <!-- 倒计时指示器 -->
          <div class="countdown" v-if="nextWordTimer > 0">
            <div class="countdown-bar" :style="{ width: (nextWordTimer / 2) * 100 + '%' }"></div>
            <p class="countdown-text">自动跳转倒计时：{{ nextWordTimer }}秒</p>
          </div>
        </div>

        <!-- 空状态 -->
        <div class="empty-state" v-if="!loading && selectedBookId && reviewWords.length === 0">
          <p>当前词汇本暂无单词数据，请选择其他词汇本</p>
        </div>
      </div>
    </main>

    <!-- 底部区域 -->
    <footer class="app-footer">
      <div class="container footer-container">
        <div class="footer-info">
          <p class="copyright">© 2025 AI辅助学习系统 版权所有</p>
          <div class="footer-links">
            <router-link to="/system-info" class="footer-link">系统说明</router-link>
            <router-link to="/help" class="footer-link">使用帮助</router-link>
            <router-link to="/contact" class="footer-link">联系我们</router-link>
          </div>
        </div>
      </div>
    </footer>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, computed, onUnmounted, watch } from 'vue';
import { useRouter } from 'vue-router';
// 导入封装的API服务
import { vocabularyApi } from '@/views/subjects/english/pages/vocabulary-study/script/vocabulary-js/vocabularyMatching.js';

// 路由实例
const router = useRouter();

// 状态管理
const isDarkMode = ref(false);
const reviewWords = ref([]); // 复习单词列表（后端数据）
const currentWordIndex = ref(0);
const showDetails = ref(false);
const currentStep = ref('word'); // 'word' 或 'spelling'
const spellingInput = ref('');
const spellingResult = ref(null);
const spellingInputRef = ref(null); 
const nextWordTimer = ref(0); // 自动跳转倒计时
let timerId = null; // 计时器ID

// API相关状态
const loading = ref(false);
const bookList = ref([]); // 词汇本列表，格式: { bookId: number, bookName: string }
const selectedBookId = ref(''); // 选中的词汇本ID
const errorMsg = ref(''); // 错误信息

// 当前单词计算属性
// 单词格式: { id: number, word: string, pronunciation: string, definition: string, example?: string, chinese?: string }
const currentWord = computed(() => {
  return reviewWords.value[currentWordIndex.value] || {};
});

// 进度百分比
const progressPercentage = computed(() => {
  if (reviewWords.value.length === 0) return 0;
  return ((currentWordIndex.value + 1) / reviewWords.value.length * 100);
});

// 初始化
onMounted(async () => {
  // 主题初始化
  const savedTheme = localStorage.getItem('vocabTheme');
  if (savedTheme) {
    isDarkMode.value = savedTheme === 'dark';
    document.documentElement.classList.toggle('dark-theme', isDarkMode.value);
  }

  // 加载词汇本列表
  try {
    loading.value = true;
    bookList.value = await vocabularyApi.getVocabBooks();
    errorMsg.value = '';
    
    // 默认选择第一个词汇本
    if (bookList.value.length > 0) {
      selectedBookId.value = bookList.value[0].bookId.toString();
    }
  } catch (err) {
    errorMsg.value = err instanceof Error ? err.message : '加载词汇本失败';
  } finally {
    loading.value = false;
  }
});

// 监听词汇本变化，加载对应单词
watch(selectedBookId, async (newBookId) => {
  if (newBookId) {
    await loadReviewWords(Number(newBookId));
  } else {
    // 清空复习数据
    reviewWords.value = [];
    currentWordIndex.value = 0;
  }
});

// 组件卸载时清除计时器
onUnmounted(() => {
  if (timerId) {
    clearInterval(timerId);
  }
});
//这是页面跳转关键逻辑
const goTo = (path) => {
  router.push(path);
};
// 从后端加载复习词汇
const loadReviewWords = async (bookId) => {
  try {
    loading.value = true;
    errorMsg.value = '';
    
    // 调用API获取指定词汇本的单词
    const fetchedWords = await vocabularyApi.getWordsByBookId(bookId);
    
    // 过滤有效单词并打乱顺序
    reviewWords.value = fetchedWords
      .filter(word => !!word.word && !!word.definition)
      .sort(() => Math.random() - 0.5);
    
    // 重置复习进度
    currentWordIndex.value = 0;
    currentStep.value = 'word';
    showDetails.value = false;
  } catch (err) {
    errorMsg.value = err instanceof Error ? err.message : '加载复习单词失败';
    reviewWords.value = [];
  } finally {
    loading.value = false;
  }
};

// 处理词汇本选择变化
const handleBookChange = () => {
  // 由watch监听触发加载
};

// 切换主题
const toggleTheme = () => {
  isDarkMode.value = !isDarkMode.value;
  document.documentElement.classList.toggle('dark-theme', isDarkMode.value);
  localStorage.setItem('aiLearnTheme', isDarkMode.value ? 'dark' : 'light');
};

// 返回词汇列表
const backToList = () => {
  if (timerId) {
    clearInterval(timerId);
  }
  router.push('/vocabulary');
};

// 标记为已掌握
const markAsKnown = () => {
  console.log(`单词 "${currentWord.value.word}" 标记为：已掌握`);
  startSpellingPractice();
};

// 标记为未掌握
const markAsUnknown = () => {
  console.log(`单词 "${currentWord.value.word}" 标记为：未掌握`);
  startSpellingPractice();
};

// 开始拼写练习
const startSpellingPractice = () => {
  currentStep.value = 'spelling';
  spellingInput.value = '';
  spellingResult.value = null;
  nextWordTimer.value = 0;
  
  // 聚焦到拼写输入框
  nextTick(() => {
    if (spellingInputRef.value) spellingInputRef.value.focus();
  });
};

// 检查拼写
const checkSpelling = () => {
  if (spellingInput.value.trim() === '') return;
  
  spellingResult.value = spellingInput.value.toLowerCase() === currentWord.value.word.toLowerCase();
  
  if (spellingResult.value) {
    startNextWordTimer();
  }
};

// 开始下一个单词倒计时
const startNextWordTimer = () => {
  if (timerId) {
    clearInterval(timerId);
  }
  
  nextWordTimer.value = 2; // 设置2秒倒计时
  
  timerId = setInterval(() => {
    nextWordTimer.value--;
    
    if (nextWordTimer.value <= 0) {
      clearInterval(timerId);
      nextWord();
    }
  }, 1000);
};

// 重置拼写练习
const resetSpelling = () => {
  if (timerId) {
    clearInterval(timerId);
  }
  
  spellingInput.value = '';
  spellingResult.value = null;
  nextWordTimer.value = 0;
  if (spellingInputRef.value) spellingInputRef.value.focus();
};

// 下一个单词
const nextWord = () => {
  if (timerId) {
    clearInterval(timerId);
  }
  
  if (currentWordIndex.value < reviewWords.value.length - 1) {
    currentWordIndex.value++;
  } else {
    // 完成所有单词复习
    alert('恭喜！你已经完成了所有单词的复习。');
    router.push('/vocabulary');
    return;
  }
  
  // 重置状态
  currentStep.value = 'word';
  showDetails.value = false;
  spellingInput.value = '';
  spellingResult.value = null;
  nextWordTimer.value = 0;
};
</script>

<style scoped>
/* 基础样式变量 */
:root {
  --primary-color: #4f46e5;
  --primary-light: #818cf8;
  --secondary-color: #10b981;
  --warning-color: #f59e0b;
  --error-color: #ef4444;
  --text-primary: #1f2937;
  --text-secondary: #6b7280;
  --bg-primary: #ffffff;
  --bg-secondary: #f9fafb;
  --border-color: #e5e7eb;
  --card-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
  --transition-speed: 0.3s;
}

.dark-theme {
  --text-primary: #f3f4f6;
  --text-secondary: #d1d5db;
  --bg-primary: #111827;
  --bg-secondary: #1f2937;
  --border-color: #374151;
  --card-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.2);
}

.review-app {
  min-height: 100vh;
  background-color: var(--bg-secondary);
  color: var(--text-primary);
  transition: background-color var(--transition-speed);
}

.container {
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  padding: 0 16px;
}

/* 头部样式 */
.app-header {
  background-color: var(--bg-primary);
  border-bottom: 1px solid var(--border-color);
  padding: 12px 0;
  transition: all var(--transition-speed);
}

.header-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.logo-container {
  width: 60px;
  height: 60px;
}

.placeholder-logo {
  width: 100%;
  height: 100%;
  background-color: var(--primary-color);
  color: white;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}

.logo-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 30px;
}

.system-title {
  flex: 1;
  margin: 0 20px;
}

.system-title h1 {
  font-size: 1.4rem;
  font-weight: 600;
  color: var(--text-primary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.theme-control {
  padding: 8px;
}

.function-buttons {
  display: flex;
  gap: 8px;
}

.func-btn, .theme-btn {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: none;
  background-color: var(--bg-secondary);
  color: var(--text-primary);
  font-size: 1rem;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.func-btn:hover, .theme-btn:hover {
  transform: scale(1.1);
  background-color: var(--primary-color);
  color: white;
}

/* 词汇本选择器 */
.book-selector {
  width: 100%;
  max-width: 600px;
  margin: 0 auto 30px;
  padding: 15px;
  background-color: var(--bg-primary);
  border-radius: 8px;
  box-shadow: var(--card-shadow);
}

.book-select {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  background-color: var(--bg-secondary);
  color: var(--text-primary);
  font-size: 1rem;
  cursor: pointer;
  transition: border-color 0.2s;
}

.book-select:focus {
  outline: none;
  border-color: var(--primary-color);
}

/* 主内容区 */
.review-content {
  padding: 40px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 进度条 */
.review-progress {
  width: 100%;
  margin-bottom: 40px;
}

.progress-bar {
  height: 8px;
  background-color: var(--primary-color);
  border-radius: 4px;
  transition: width 0.5s ease;
}

.progress-text {
  font-size: 14px;
  color: var(--text-secondary);
  margin-top: 8px;
  text-align: center;
}

/* 单词卡片 */
.word-card {
  width: 100%;
  max-width: 600px;
  background-color: var(--bg-primary);
  border-radius: 16px;
  box-shadow: var(--card-shadow);
  padding: 40px;
  text-align: center;
  transition: all var(--transition-speed);
  margin: 0 auto;
}

.word-display {
  margin-bottom: 30px;
}

.review-word {
  font-size: 2.5rem;
  font-weight: 600;
  color: var(--primary-color);
  margin: 0 0 10px 0;
}

.review-pronunciation {
  font-size: 1.2rem;
  color: var(--text-secondary);
  margin: 0;
}

.review-chinese {
  font-size: 1.1rem;
  color: var(--text-primary);
  margin: 10px 0 0;
  font-weight: 500;
}

.word-details {
  margin-bottom: 30px;
  text-align: left;
  opacity: 0;
  max-height: 0;
  overflow: hidden;
  transition: all 0.3s ease;
}

.word-details.active {
  opacity: 1;
  max-height: 300px;
  margin-top: 20px;
}

.review-definition {
  font-size: 1.2rem;
  line-height: 1.6;
  margin: 0 0 20px 0;
}

.review-example {
  font-size: 1rem;
  line-height: 1.6;
  margin: 0;
  color: var(--text-secondary);
}

.toggle-details-btn {
  padding: 12px 30px;
  background-color: var(--primary-color);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  cursor: pointer;
  transition: all 0.2s ease;
  margin-bottom: 20px;
}

.toggle-details-btn:hover {
  background-color: var(--primary-light);
  transform: translateY(-2px);
}

.review-actions {
  display: flex;
  gap: 20px;
  justify-content: center;
}

.action-btn {
  padding: 12px 24px;
  border-radius: 8px;
  border: none;
  font-size: 1rem;
  cursor: pointer;
  transition: all 0.2s;
  font-weight: 500;
}

.know-btn {
  background-color: var(--secondary-color);
  color: white;
}

.unknown-btn {
  background-color: var(--warning-color);
  color: white;
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

/* 拼写练习区 */
.spelling-practice {
  width: 100%;
  max-width: 600px;
  background-color: var(--bg-primary);
  border-radius: 16px;
  box-shadow: var(--card-shadow);
  padding: 40px;
  text-align: center;
  transition: all var(--transition-speed);
}

.spelling-title {
  font-size: 1.5rem;
  font-weight: 600;
  margin: 0 0 20px 0;
}

.spelling-hint {
  font-size: 1.2rem;
  margin: 0 0 30px 0;
  color: var(--text-secondary);
}

.spelling-input {
  width: 100%;
  padding: 14px 20px;
  border: 2px solid var(--border-color);
  border-radius: 8px;
  background-color: var(--bg-secondary);
  color: var(--text-primary);
  font-size: 1.5rem;
  text-align: center;
  margin-bottom: 20px;
  transition: all 0.2s;
}

.spelling-input:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
}

.spelling-input.correct-input {
  border-color: var(--secondary-color);
  background-color: rgba(16, 185, 129, 0.1);
}

.spelling-input.incorrect-input {
  border-color: var(--error-color);
  background-color: rgba(239, 68, 68, 0.1);
}

.spelling-feedback {
  margin-bottom: 30px;
  font-size: 1.2rem;
  font-weight: 500;
  min-height: 24px;
}

.correct {
  color: var(--secondary-color);
}

.incorrect {
  color: var(--error-color);
}

.spelling-actions {
  display: flex;
  gap: 20px;
  justify-content: center;
}

.retry-btn {
  background-color: var(--warning-color);
  color: white;
}

.next-btn {
  background-color: var(--primary-color);
  color: white;
}

/* 倒计时指示器 */
.countdown {
  margin-top: 20px;
}

.countdown-bar {
  height: 4px;
  background-color: var(--primary-color);
  border-radius: 2px;
  transition: width 1s linear;
}

.countdown-text {
  font-size: 14px;
  color: var(--text-secondary);
  margin-top: 8px;
}

/* 底部样式 */
.app-footer {
  background-color: var(--bg-primary);
  border-top: 1px solid var(--border-color);
  padding: 24px 0;
  margin-top: 60px;
}

.footer-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.footer-info {
  text-align: center;
}

.copyright {
  font-size: 14px;
  color: var(--text-secondary);
  margin: 0 0 12px 0;
}

.footer-links {
  display: flex;
  gap: 20px;
}

.footer-link {
  font-size: 14px;
  color: var(--primary-color);
  text-decoration: none;
  transition: color 0.2s;
}

.footer-link:hover {
  color: var(--primary-light);
  text-decoration: underline;
}

/* 加载和空状态 */
.loading-indicator {
  text-align: center;
  padding: 60px 0;
  color: var(--text-secondary);
  font-size: 1.1rem;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
  color: var(--text-secondary);
  font-size: 1.1rem;
  background-color: var(--bg-primary);
  border-radius: 8px;
  margin-top: 20px;
}

.error-message {
  color: var(--error-color);
  font-size: 0.9rem;
  margin-top: 8px;
  display: block;
}

/* 暗色主题适配 */
.dark-theme .review-app {
  --bg-secondary: #1f2937;
  --bg-primary: #374151;
  --text-primary: #f3f4f6;
  --text-secondary: #d1d5db;
  --border-color: #4b5563;
  --card-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.3);
}

.dark-theme .func-btn:hover,
.dark-theme .theme-btn:hover,
.dark-theme .toggle-details-btn:hover,
.dark-theme .action-btn:hover {
  background-color: var(--primary-light);
}

.dark-theme .spelling-input {
  background-color: var(--bg-primary);
  border-color: var(--border-color);
}

.dark-theme .spelling-input:focus {
  border-color: var(--primary-light);
}

/* 响应式调整 */
@media (max-width: 600px) {
  .system-title h1 {
    font-size: 1.1rem;
  }
  
  .review-word {
    font-size: 2rem;
  }
  
  .word-card, .spelling-practice {
    padding: 25px 15px;
  }
  
  .action-btn {
    padding: 10px 20px;
    font-size: 0.9rem;
  }
}
</style>
    